package org.wkg.lesson08;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 自定义定时器
 * 1.定义一个类，存放任务与任务时间
 * 2.定义一个阻塞队列来存储任务
 * 3.提供一个方法可以提交任务
 * 4.要有一个线程任务
 *
 * @Author 比特就业课
 */


public class MyTimer_4 {
    private BlockingQueue<MyTask04> queue = new PriorityBlockingQueue<>();

    public MyTimer_4() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    MyTask04 myTask04 = this.queue.take();

                    long currentTime = System.currentTimeMillis();
                    /*if (currentTime >= myTask04.getTime()) {
                        // 时间到了，执行任务
                        myTask04.getRunnable().run();
                    } else {
                        queue.put(myTask04);
                    }*/
                    /**
                     * 为什么上面代码可以正常执行延迟任务而下面的任务就没法正常执行延迟任务，而是直接把所有任务都执行完？
                     */

                    if (myTask04.getTime() <= System.currentTimeMillis()) {
                        myTask04.getRunnable().run();
                    } else {
                        queue.put(myTask04);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }


    public void schedule(Runnable runnablem, long delay) throws InterruptedException {
        MyTask04 myTask04 = new MyTask04(runnablem, delay);
        queue.put(myTask04);
    }

}

class MyTask04 implements Comparable<MyTask04> {
    private Runnable runnable;
    private long time;

    public MyTask04(Runnable runnable, long delay) {
        if (runnable == null) {
            throw new IllegalArgumentException("任务不能为null");
        }
        if (delay < 0) {
            throw new IllegalArgumentException("任务时间不能为小于0");
        }
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }


    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }


    //系统中如何获取getTime()与o.getTime()，然后进行比较的，请你把底层是如何运行的由浅入深的讲解一下
    @Override
    public int compareTo(MyTask04 o) {
        if (getTime() > o.getTime()) {
            return 1;
        } else if (getTime() < o.getTime()) {
            return -1;
        } else {
            return 0;
        }
    }
}













